//index.js
const app = getApp()
const Url = app.url
const util = require('../../../utils/util.js')

Page({
	data: {
		customerWxId: '', // openId
		myCouponList: [], // 我的优惠券列表
	},

	onShow: function () {
		this.setCustomerWxId()
		this.getMyCouponList()
	},

	// 跳转到优惠券列表页面
	jumpToCouponListPage: function () {
		console.log(1111)
		wx.navigateTo({
			url: '../allCoupon/index?time=' + new Date(),
		})
	},

	// 跳转到优惠券二维码页面
	jumpToCouponQrCodePage: function (event) {
		const couponNum = event.currentTarget.dataset.conpon
		const couponLogo = event.currentTarget.dataset.logo
		const couponName = event.currentTarget.dataset.name
		wx.navigateTo({
			url: `../../home/couponQrCode/index?couponNum=${couponNum}&couponLogo=${couponLogo}&couponName=${couponName}`,
		})
	},

	// 设置openid
	setCustomerWxId: function () {
		if (!!wx.getStorageSync('openid')) {
			this.setData({
				customerWxId: wx.getStorageSync('openid'),
			})
		} else {
			wx.login({
				success: (res) => {
					wx.setStorageSync('codeMes', res.code)
					util.getOpenId(Url.login)
					this.setData({
						customerWxId: wx.getStorageSync('openid'),
					})
				},
			})
		}
	},

	// 获取优惠券列表
	getMyCouponList: function () {
		let that = this
		wx.showLoading({
			title: '加载中',
			mask: true,
		})

		wx.request({
			url: Url.myCouponList + `?customerWxId=${that.data.customerWxId}`,
			method: 'GET',
			data: {},
			header: {
				'content-type': 'application/json',
			},
			success: function (res) {
				wx.hideLoading()
				console.log(res, 'res')
				if (res.data.code == '200') {
					const couponList = res.data.model || []
					console.log(couponList, 'couponList')
					couponList.forEach((item) => {
						item.coupon.config = JSON.parse(item.coupon.config)
						item.effectiveStartTime = item.effectiveStartTime.split(
							' '
						)[0]
						item.effectiveEndTime = item.effectiveEndTime.split(
							' '
						)[0]
					})
					that.setData({
						myCouponList: couponList,
					})
				} else {
					wx.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 2000,
					})
				}
			},
			fail: function (err) {
				wx.hideLoading()
				console.log(err)
				wx.showToast({
					title: err.errMsg,
					icon: 'none',
					duration: 2000,
				})
			},
		})
	},
})
